import os
import hashlib
from userdefaults import user_data

md5_suf = "md5"


def read_md5_info():
    path = os.getcwd()
    md5_path = None
    for item in os.listdir(path):
        if item.lower().endswith(md5_suf):
            md5_path = item
    assert md5_path is not None, '找不到md5信息文件'
    md5_full_path = os.path.join(os.getcwd(), md5_path)
    md5_info = {}
    with open(md5_full_path, 'r') as f:
        while True:
            line_content = f.readline()
            if line_content is None or len(line_content) == 0:
                break
            line_content = line_content.strip()
            res_list = line_content.split(" *")
            if len(res_list) == 2:
                md5_info[res_list[0]] = res_list[-1]
    return md5_info


def get_md5_code(file_path: str) -> str:
    if file_path.startswith(os.sep) or file_path.startswith('.'):
        pass
    else:
        file_path = os.path.join('.', file_path)
    with open(file_path, 'rb') as f:
        value = hashlib.md5(f.read()).hexdigest()
        return value


def check_files(info: dict):
    files = os.listdir(os.getcwd())

    for k, v in info.items():
        for file in files:
            check_val = user_data.object_for_key(v)
            if check_val == 1:
                print(f"{file} has already been checked correctly")
                continue
            else:
                if file.endswith(v):
                    print("Target found, start cal")
                    code = get_md5_code(file)
                    checked = (code == k)
                    if checked:
                        print(f"{file} is complete")
                    else:
                        print(f"{file} is incomplete")
                    user_data.save_object(v, checked)


if __name__ == '__main__':
    g_info = read_md5_info()
    print(g_info)
    check_files(g_info)